package com.llb.llbliving.commodity.service.impl;

import com.llb.llbliving.commodity.entity.*;
import com.llb.llbliving.commodity.service.*;
import com.llb.llbliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llb.common.utils.PageUtils;
import com.llb.common.utils.Query;

import com.llb.llbliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    /*
    * 保存SpuSaveV0 对象/数据[会根据业务，将数据分别保存对应表]
    * 涉及到多表的添加，因此需要进行事务管理
    * */
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        //1.保存spu基本信息到 表commodity_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //2.将spuSaveV0对象的属性组对拷到spuInfoEntity对象
        BeanUtils.copyProperties(spuSaveVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //3.将spuInfoEntity保存到数据库
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存spu的介绍图片的信息
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //这里我们设置给spuInfoDescEntity对象的spuId就是上面添加的spuInfoEntity对应的id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

        if(decript.size()==0){//没有spu对应的介绍图片-设置一个默认图片
            spuInfoDescEntity.setDecript("default.jpg");
        }else{//String.join(",",decript)这个是把decript这个链表里的元素以逗号分隔，然后返回string
            spuInfoDescEntity.setDecript(String.join(",",decript));
        }

        //保存spuInfoDescEntity
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //保存spu对应的图片集
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //保存spu对应的基本属性[一个spu可以有多个基本属性]
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setAttrSort(0);
            //通过attrid获取到attrentity的name
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);

        //保存sku基本的信息
        List<Skus> skus = spuSaveVO.getSkus();

        if(skus!=null&&skus.size()>0){
            skus.forEach((item)->{
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                String defaultImg="default.img";
                for(Images image:item.getImages()){
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }
                }
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setPrice(item.getPrice());
                skuInfoEntity.setSkuName(item.getSkuName());
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSkuTitle(item.getSkuTitle());
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //保存sku的图片集信息到commodity_sku_images
                //一个sku可以对应多个图片
                List<SkuImagesEntity> collect = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).filter(img->{
                    return StringUtils.isNotBlank(img.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);
                //保存sku的销售属性
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(obj -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(obj.getAttrId());
                    skuSaleAttrValueEntity.setAttrValue(obj.getAttrValue());
                    skuSaleAttrValueEntity.setAttrName(obj.getAttrName());
                    skuSaleAttrValueEntity.setAttrSort(0);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });
        }
    }

    /*
    * 保存spu的基本信息
    * */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();//按检索条件-spu 名字
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{ //注意这里的 and 会把后面两个条件括起来
                w.eq("id",key).or().like("spu_name",key);
            });
        }
//加入状态
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
//加入品牌 id
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
//加入分类 id
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){wrapper.eq("catalog_id",catelogId);
        }
//分页查询
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId,1);
    }

    @Override
    public void down(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId,2);
    }
}